import Vue from 'vue'
import Router from 'vue-router'

const Home = () => import('views/home/Home')
const Category = () => import('views/category/Category')
const ShopCart = () => import('views/shopcart/ShopCart')
const Profile = () => import('views/profile/Profile')
const Detail = () => import('../views/detail/Detail.vue')

//处理重复路由报错
//获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

//1. 安装插件
Vue.use(Router)

//2.创建router
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    meta: {
      title: '首页'
    }
  },
  {
    path: '/category',
    component: Category,
    meta: {
      title: '分类'
    }
  },
  {
    path: '/shopcart',
    component: ShopCart,
    meta: {
      title: '购物车'
    }
  },
  {
    path: '/profile',
    component: Profile,
    meta: {
      title: '个人中心'
    }
  },
  {
    path: '/detail/:id',
    component: Detail,
    meta: {
      title: '详情页'
    }
  }
]
const router = new Router({
  routes,
  mode: 'history'
})

//布置全局守卫
router.beforeEach((to, from, next) => {
  // 进入之前获取标题数据
  if (to.matched[0].meta.title) {
    document.title = to.matched[0].meta.title
  }
  next()
})

//3. 导出
export default router
